package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.PricingManager;
import com.xyzh05.model.Pricing;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class PricingAction extends BaseAction implements Preparable {
    private PricingManager pricingManager;
    private List pricings;
    private Pricing pricing;
    private Long id;
    private String query;

    public void setPricingManager(PricingManager pricingManager) {
        this.pricingManager = pricingManager;
    }

    public List getPricings() {
        return pricings;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String pricingId = getRequest().getParameter("pricing.id");
            if (pricingId != null && !pricingId.equals("")) {
                pricing = pricingManager.get(new Long(pricingId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        pricings = pricingManager.search(query, Pricing.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Pricing getPricing() {
        return pricing;
    }

    public void setPricing(Pricing pricing) {
        this.pricing = pricing;
    }

    public String delete() {
        pricingManager.remove(pricing.getId());
        saveMessage(getText("pricing.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            pricing = pricingManager.get(id);
        } else {
            pricing = new Pricing();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (pricing.getId() == null);

        pricingManager.save(pricing);

        String key = (isNew) ? "pricing.added" : "pricing.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}